<template>
  <div class="root-box" id="FortenCollapse">

    <!--分组过滤-->
    <van-row>
      <van-col span="24">
        <van-field v-model="groupSearchValue" input-align="right" label-width="0" readonly clearable>
          <template #button>
            <van-button plain type="primary" size="mini" @click="openGroupSearch" style="    height: 22px;    width: auto; padding: 2px 9px;">筛选</van-button>
            <van-button plain   size="mini" @click="groupSearchValue = ''" style="    height: 22px;    width: auto; padding: 2px 9px;">重置</van-button>
            <van-button plain type="primary" size="mini" @click="collapseGroup" style="    height: 22px;    width: auto; padding: 2px 9px;">{{isCollapseGroup ? '折叠' : '展开'}}</van-button>
          </template>
        </van-field>
      </van-col>
    </van-row>

    <!--一级-->
    <van-collapse v-model="activeNames" v-for="groupOb in cpGroupUnq" :key="groupOb.value" :name="groupOb.value" @change="collapse2Change">
      <van-collapse-item
        :key="groupOb.value"
        :name="groupOb.value">
        <template #title>
          <strong style="font-size: 14px;margin-left: 10px;">{{groupOb.text}} </strong>
          <span style="font-size: 14px;color:gray;">{{cpPickedQty(groupOb.items)}}</span>

          <strong  style="float: right"></strong>
        </template>

        <template>

          <!--二级-->
          <van-collapse v-model="groupOb.activeNames" >
            <van-collapse-item
              v-for="(item,index) in groupOb.items"
              :key="item[pkName]"
              :is-link="false"
              :name="item[pkName]">
              <template #title>
                <slot :item="item" name="title">
                  <small v-if="titleWarningText">{{titleWarningText}}：</small>
                  <van-tag style="margin-right: 9px;" type="warning" plain     v-if="titleWarningField">{{strings.defaultIfBlank(item[titleWarningField],'0')}}</van-tag>

                  <small v-if="titleDangerText">{{titleDangerText}}：</small>
                  <van-tag style="margin-right: 9px;" type="danger" plain     v-if="titleDangerField">{{ strings.defaultIfBlank(item[titleDangerField],'0')}}</van-tag>

                  <small v-if="titleSuccessText">{{titleSuccessText}}：</small>
                  <van-tag style="margin-right: 9px;" type="success" plain     v-if="titleSuccessField">{{strings.defaultIfBlank(item[titleSuccessField],'0')}}</van-tag>
                </slot>
              </template>
              <template>
                <div @click="userOp(item, 'click')" >
                  <slot :item="item" >
                      <van-row>
                        <van-col span="24">创建时间:{{item.gmtCreate}}</van-col>
                      </van-row>
                      <van-row>
                        <van-col span="12">调拨单号:{{item.busKey}}</van-col>
                        <van-col span="12">标签数:{{item.labelQty}}</van-col>
                      </van-row>
                      <van-row>
                        <van-col span="12">配送仓库:{{item.fromWarehouseName}}</van-col>
                      </van-row>
                      <van-row>
                        <van-col span="12">制单人:{{item.busUser}}</van-col>
                        <van-col span="12">拣货人:{{item.picker}}</van-col>
                      </van-row>
                  </slot>
                  <van-divider
                    :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 8px', margin: '5px 0 0' }"
                    v-if="index < groupOb.items.length-1 "
                  ></van-divider>
                </div>
              </template>
            </van-collapse-item>
          </van-collapse>
        </template>
      </van-collapse-item>
    </van-collapse>

   <!-- 分组过滤-->
    <FortenList ref="listItem" :propAutoFetchData="false"  :propFlagStatic="true"  :propFlagNoPage="true"
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['text']"
                :propSearchTextAppend="groupText"
                @change="change"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="20">{{item.text}}</van-col>
        </van-row>
      </template>
    </FortenList>
  </div>
</template>

<script>
export default {
  title: '折叠组件',
  name: 'FortenCollapse',
  data() {
    return {
      //当前激活的
      activeNames: [],

      //原始数据
      items: [],

      //分组数据列，唯一的
      groupUnq: [],


      groupSearchData: [],
      groupSearchValue: '',
      isCollapseGroup: false,
      groupUnqValue: []
    }
  },

  props: [
    'pkName',             //数据主键名称
    'clickTo',
    /* 点击后跳转的路由，将执行
     this.$router.push({
        name: clickTo,
      params: item
    })
    */
    'titleWarningField',   //标题警告字段
    'titleWarningText',   //标题警告字段
    'titleDangerField',   //标题警告字段
    'titleDangerText',   //标题警告字段
    'titleSuccessField',   //标题成功字段
    'titleSuccessText',   //标题成功字段
    'titleTextField',     //标题文本字段
    'titleText',          //标题文本标题
    'groupValueField',          //分组字段主键
    'groupTextField',          //分组字段主键
    'groupText',          //分组字段标题
    'keepActive',          //true 保留一级容器展开状态
  ],
  methods: {
    setData(itemsParam) {
      if (this.strings.isBlank(this.groupValueField)) {
        console.error('当前仅实现了分组，请传递参数：groupValueField')
        return
      }
      this.items = itemsParam

      // groupItems
      this.items.forEach(ob => {
        if (!this.groupUnqValue.includes(ob[this.groupValueField])) {
          let itemsFind = this.items.filter(ob2 => ob2[this.groupValueField] == ob[this.groupValueField])
          let activeNames = []
          itemsFind.forEach(ob3 => activeNames.push(ob3[this.pkName]))
          this.groupUnq.push({
            value: ob[this.groupValueField],
            text: ob[this.groupTextField],
            items: itemsFind,
            'activeNames': activeNames
          })
          this.groupUnqValue.push(ob[this.groupValueField])
          this.groupSearchData.push({text: ob[this.groupTextField]})
        }
      })


      this.$refs.listItem.list =  this.groupSearchData
    },

    userOp(item, type) {
      if (this.strings.isNotBlank(this.clickTo)) {
        this.$router.push({
          name: this.clickTo,
          params: item
        })
        return
      }
      this.$emit('call', {'item': item, 'type': type})
    },

    //分组条件选择后
    change(item) {
      this.groupSearchValue = item.text
    },

    openGroupSearch() {
      this.$refs.listItem.show()
    },

    //展开或者折叠
    collapseGroup() {
      if (this.isCollapseGroup) {
        this.activeNames = []
      } else {
        this.activeNames = this.groupUnqValue
      }
      this.isCollapseGroup = !this.isCollapseGroup
      this.setlocalStorageStatus()
    },

    //一级容器展开折叠状态变化
    collapse2Change() {
      if (this.keepActive) {
        setTimeout(() => {
          this.setlocalStorageStatus()
        }, 500)
      }
    },

    setlocalStorageStatus() {
      let fullPath = this.$route.fullPath
      localStorage.setItem('forten_collapse_active_' + fullPath, this.activeNames.join(','))
      localStorage.setItem('forten_collapse_is_collapse_group_' + fullPath, this.isCollapseGroup)
    }
  },
  created() {
    if (this.keepActive) {
      let fullPath = this.$route.fullPath
      let activeNamesGet = localStorage.getItem('forten_collapse_active_' + fullPath)
      let isCollapseGroupGet = localStorage.getItem('forten_collapse_is_collapse_group_' + fullPath)
      if (this.strings.isNotBlank(activeNamesGet)) {
        let activeNamesGetArr = activeNamesGet.split(',')
        this.activeNames = activeNamesGetArr
      }

      if (isCollapseGroupGet && (isCollapseGroupGet == 'true' || isCollapseGroupGet == true)) {
        this.collapseGroup()
      }
    }
  },
  computed: {
    cpGroupUnq() {
      if (this.strings.isBlank(this.groupSearchValue)) {
        return this.groupUnq
      }
      return this.groupUnq.filter(ob => ob.text == this.groupSearchValue)
    },
    cpPickedQty() { 
      return (items) => {
        let txt = ''
        if (this.titleWarningField) {
          let warningVal = 0
          items.forEach(item => warningVal += item[this.titleWarningField])
          txt += warningVal + '/'
        }

        if (this.titleDangerField) {
          let dangerVal = 0
          items.forEach(item => dangerVal += item[this.titleDangerField])
          txt += dangerVal + '/'
        }

        if (this.titleSuccessField) {
          let successVal = 0
          items.forEach(item => successVal += item[this.titleSuccessField])
          txt += successVal + '/'
        }

        if (txt.length > 0) {
          return txt.slice(0, txt.length - 1)
        }
        return txt
      }
    }
  },
}
</script>

<style lang="scss">
  .van-cell::after {
    border-bottom: 0px solid #ebedf0 !important;
  }
  .van-cell:not(:last-child)::after {
    border-bottom: 0px solid #ebedf0 !important;
  }
</style>
